package leetcode.editor.cn.test;

import leetcode.editor.cn.common.ListNode;

public class mergeTwoLists_21 {

    public static ListNode mergeTwoLists(ListNode list1, ListNode list2) {
        ListNode node = new ListNode(-1);
        ListNode p = node; // 指针
        // 利用双指针
        while (list1 != null || list2 != null) {
            if (list1 == null){
                p.next = list2;
                list2 = list2.next;
                p = p.next;
                continue;
            }else if (list2 == null){
                p.next = list1;
                list1 = list1.next;
                p = p.next;
                continue;
            }
            if (list1.val <= list2.val) {
                p.next = list1;
                list1 = list1.next;
            } else {
                p.next = list2;
                list2 = list2.next;
            }
            p = p.next;// 指针前进
        }
        return node.next; // 返回时去掉虚拟头结点
    }
    public static void main(String[] args) {
        ListNode list1 = ListNode.createListNode(new int[]{1,2,4});
        ListNode list2 = ListNode.createListNode(new int[]{1,3,4});
        ListNode merged = mergeTwoLists(list1, list2);
        ListNode.printLinkedList(merged);
    }
}
